
package com.yuanxiao.controller;

import com.yuanxiao.dao.AuthCodeDao;
import com.yuanxiao.feign.EmailSErviceClient;
import com.yuanxiao.pojo.AuthCode;
import com.yuanxiao.service.EmailService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Optional;

@RestController
@RequestMapping("/api/code")
public class CodeController {
    @Autowired
    private EmailSErviceClient emailSErviceClient;
    @Autowired
    private AuthCodeDao authCodeDao;

    @Reference(timeout = 50000)
    private EmailService emailService1;

    @GetMapping("/create/{email}")
    public Boolean createCode(@PathVariable String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        String code = RandomStringUtils.random(4, "0123456789abcdejkljiuiuowmcxz");
        //Boolean sendEmail = emailSErviceClient.sendEmail(email, code);
        Boolean sendEmail = emailService1.sendEmail(email, code);
        if (sendEmail) {//此处用redis做最佳
            //发送后情况旧的验证码
            authCodeDao.deleteByEmail(email);
            //插入新的验证码以及失效时间
            authCodeDao.save(new AuthCode().setEmail(email).setCode(code).setCreateTime(new Date())
                    .setExpireTime(new Date(System.currentTimeMillis() + 10 * 60 * 1000)));
        }
        return true;
    }
}
/*
    @GetMapping("/validate/{email}/{code}")
    public Boolean validateCode(@PathVariable String email, @PathVariable String code){
        if (StringUtils.isEmpty(email)){
            return false;
        }
        if (StringUtils.isEmpty(code)) {
            return false;

        }
        boolean flag=false;
        Optional<AuthCode> one = authCodeDao.findOne(Example.of(new AuthCode().setEmail(email).setCode(code)));
        if (one.isPresent()){
            //有数据,判断是否过期
            flag=  one.get().getExpireTime().compareTo(new Date())>=0?true:false;
            if(flag){
                //为真说明正确,删除该验证码
                authCodeDao.deleteByEmail(email);
            }

        }

        return flag;
    }
}
*/
